﻿using Caliburn.Micro;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using ThunderboltInterfaceSharp.ViewModels;

namespace ThunderboltInterfaceSharp;

public class ProgramBootstrapper : BootstrapperBase
{
	public ProgramBootstrapper()
	{
		Initialize();
	}


	protected override void OnStartup(object sender, StartupEventArgs e)
	{
		var instance = GetRunningInstance();
		if (GetRunningInstance() != null)
		{
			HandleRunningInstance(instance);
			Application.Current.Shutdown();
			return;
		}
		DisplayRootViewForAsync<ThunderStartViewModel>();//显示界面
	}
	protected override void OnExit(object sender, EventArgs e)
	{
		Environment.Exit(0);
	}
	#region 进程唯一
	[DllImport("User32.dll")]
	private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
	[DllImport("User32.dll")]
	private static extern bool SetForegroundWindow(IntPtr hWnd);
	public static Process? GetRunningInstance()
	{
		//获取当前进程
		var currentProcess = Process.GetCurrentProcess();
		var currentFileName = currentProcess.MainModule.FileName;
		//创建新的 Process 组件的数组，并将它们与本地计算机上共享指定的进程名称的所有进程资源关联。
		var processes = Process.GetProcessesByName(currentProcess.ProcessName);
		//查找有相同名字运行的进程
		return processes.ToList().FirstOrDefault(x => x.MainModule.FileName == currentFileName && x.Id != currentProcess.Id);
	}
	
	public static void HandleRunningInstance(Process instance)
	{
		ShowWindowAsync(instance.MainWindowHandle, 1);
		SetForegroundWindow(instance.MainWindowHandle);
	}
	#endregion
}